package com.dzm.xgb.core.controller.api;


import com.dzm.common.result.R;
import com.dzm.common.util.JwtUtils;
import com.dzm.xgb.core.hfb.RequestHelper;
import com.dzm.xgb.core.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author Dzm
 * @since 2024-08-27
 */
@RestController
@RequestMapping("/api/core/userAccount")
public class UserAccountController {

    @Autowired
    private UserAccountService userAccountService;

    @PostMapping("/auth/commitCharge/{chargeAmt}")
    public R commitCharge(@PathVariable("chargeAmt")BigDecimal chargeAmt, @RequestHeader("token") String token) {
        Long userId = JwtUtils.getUserId(token);

        //生成提交表单
        String formStr = userAccountService.commitCharge(chargeAmt, userId);

        return R.ok().data("formStr", formStr);
    }

    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        //处理请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> map = RequestHelper.switchMap(parameterMap);

        //验签操作
        if(RequestHelper.isSignEquals(map)) {
            if("0001".equals(map.get("resultCode"))) {      //验证返回是否成功
                return userAccountService.notifyUserAccount(map);
            }

            return "fail";
        }

        return "非法访问！";
    }

    @GetMapping("/getAccount")
    public R getAccount(@RequestHeader("token") String token) {
        Long userId = JwtUtils.getUserId(token);
        BigDecimal account = userAccountService.getAccount(userId);

        return R.ok().data("account", account);
    }

    @PostMapping("/auth/commitWithdraw/{fetchAmt}")
    public R commitWithdraw(@PathVariable("fetchAmt")BigDecimal fetchAmt, @RequestHeader("token") String token) {
        String formStr = userAccountService.commitWithdraw(JwtUtils.getUserId(token), fetchAmt);

        return R.ok().data("formStr", formStr);
    }

    @PostMapping("/notifyWithdraw")
    public String notifyWithdraw(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> map = RequestHelper.switchMap(parameterMap);
        //验签
        if(RequestHelper.isSignEquals(map)) {
            if("0001".equals(map.get("resultCode"))) {
                return userAccountService.notifyWithdraw(map);
            }
            return "fail";
        }

        return "非法访问！";
    }

}

